<?php

class AbstractSelectionElement extends FormElement
{

  public $keyField;

  public $labelField;

  public $options;

  public $query;

  public $queryData;

  public $queryParams;

  public $table;

  public $defaultValue;

  public function getTable()
  {
    if (empty($this->table)) {
      $this->table = $this->form->table;
    }

    return $this->table;
  }

  public function getKeyField()
  {
    if (empty($this->keyField)) {
      $this->keyField = $this->getField();
    }

    return $this->keyField;
  }

  public function getLabelField()
  {
    if (empty($this->labelField)) {
      $this->labelField = $this->getField();
    }

    return $this->labelField;
  }

  public function getOptions()
  {
    if (is_null($this->options)) {
      if (empty($this->query)) {
        $this->query = DB::getInstance()->query()->from($this->getTable())->select($this->getKeyField(), $this->getLabelField());
      }
      elseif (is_string($this->query)) {
        $this->query = DB::getInstance()->query($this->query);
      }

      $this->query->setParams($this->queryParams);

      $result = $this->query->execute($this->queryData);

      $data = $result->fetchAll();

      $options = sy_array_to_options($data, $this->getKeyField(), $this->getLabelField());

      $options = $this->filters('options', $options, $data);

      $this->options = $options;
    }

    return $this->options;
  }

  protected function getValue(&$row)
  {
    $value = parent::getValue($row);

    if (empty($value)) {
      $value = $this->defaultValue;
    }

    return $value;
  }

}
